<template>
  <div class="build-function">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="left">
      <el-form-item
        prop="functionName"
        label="函数名称"
      >
        <el-input v-model="form.functionName" placeholder="请输入函数名称" :disabled="type==='updateFunction'" />
      </el-form-item>
      <!--      <el-form-item prop="vCPU" label="vCPU /核">-->
      <!--        <el-input v-model.number="form.vCPU" placeholder="请输入vCPU核数" disabled />-->
      <!--      </el-form-item>-->
      <el-form-item prop="memorySize" label="内存 /MB">
        <el-input
          v-model.number="form.memorySize"
          placeholder="请输入内存大小（128MB~3072MB，vCPU会自动适配）"
        />
      </el-form-item>
      <el-form-item prop="timeOut" label="超时时间 /s">
        <el-input
          v-model.number="form.timeOut"
          placeholder="请输入超时时间"
        />
      </el-form-item>
    </el-form>

    <div v-if="type !== 'steps'">
      <el-button
        v-if="type === 'createFunction'"
        type="primary"
        size="mini"
        round
        @click="createFun"
      >
        提交
      </el-button>
      <el-button v-else type="primary" size="mini" round @click="updateFun">
        修改
      </el-button>
      <el-button type="primary" size="mini" round @click="tableDrawer=true">高级设置</el-button>
      <el-button size="mini" round @click="$router.go(-1)">取消</el-button>
    </div>
    <div>
      <el-drawer
        v-loading="publicLayer===[] && activeName !== 'label1'"
        title="函数设定高级配置"
        :visible.sync="tableDrawer"
        direction="rtl"
        size="60%"
        :append-to-body="true"
      >
        <el-tabs v-model="activeName" tab-position="top" style="margin: 20px;">
          <el-tab-pane label="使用基础配置" name="label1">
            <div style="margin: 10px; font-weight: bolder; border-bottom: 1px solid #d5d5d5;">基础配置将提供函数模板，不会提前包含任何第三方库。如需使用具有基础第三方库的模板，请移步其他配置查看。</div>
          </el-tab-pane>
          <el-tab-pane label="AI基础库配置" name="label2">
            <div style="margin: 10px; font-weight: bolder; border-bottom: 1px solid #d5d5d5;">在AI基础配置中可以选择某一个配置进行开发，将为函数提前准备部分第三方库。</div>
            <div class="table-wrapper">
              <el-table :data="publicLayer" style="margin-left: 10px; margin-right: 10px;" stripe>
                <el-table-column label="基础模板" prop="name" align="left" />
                <el-table-column label="详情" type="expand" align="left">
                  <template #default="props">
                    <div class="display-window">
                      此基础库将包含以下依赖:
                      {{ props.row.contains }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template v-slot="scope">
                    <el-button
                      size="mini"
                      :disabled="buildFunctionAILayer !== '' && buildFunctionAILayer !== scope.row.arn"
                      @click="setFunctionLayer(scope.row.arn, scope.row.arn !== buildFunctionAILayer)"
                    >
                      <div v-if="scope.row.arn !== buildFunctionAILayer">
                        选择并应用
                      </div>
                      <div v-else>
                        取消应用
                      </div>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';
import { getPublicLayerForLibrary, getLayerDependencyForLibrary } from '@/api/userProjectLibrary';

/**
 * 新建函数
 */
export default {
  props: {
    type: {
      type: String,
      default: 'steps'
    },
    options: {
      type: Object,
      default: () => {
      }
    }
  },
  data() {
    return {
      desc: '',
      addParams: 0,
      form: {
        functionName: '', // 初始化函数名称为空字符串
        timeOut: 60, // 初始化超时时间为60秒
        memorySize: 256, // 初始化内存为128MB
        vCPU: 0.35// 初始化vCPU为0.35 无法更改
      },
      rules: {
        functionName: [
          { required: true, message: '函数名不能为空！', trigger: 'blur' },
          { max: 128, message: '函数名过长！', trigger: 'blur' },
          {
            pattern: /^[_a-zA-Z][-_a-zA-Z0-9]*$/,
            message: '函数名中只能包含大小写字母、数字、’_‘与’-‘，且以字母或’_‘开头',
            trigger: 'blur'
          }
        ],
        timeOut: [
          { required: true, message: '超时时间不能为空！', trigger: 'blur' },
          { type: 'number', message: '超时时间必须为数字', trigger: 'blur' },
          { validator: this.validateTimeout, trigger: 'blur' }
        ],
        memorySize: [
          { required: true, message: '内存不能为空！', trigger: 'blur' },
          { type: 'number', message: '内存必须为数字', trigger: 'blur' },
          { validator: this.validateMemory, trigger: 'blur' }
        ],
        vCPU: [
          { required: true, message: 'vCPU不能为空！', trigger: 'blur' },
          { type: 'number', message: 'vCPU必须为数字', trigger: 'blur' }
        ]
      },
      tableDrawer: false,
      publicLayer: [],
      activeName: 'label1',
      explanatoryText: '函数创建目前支持使用基础配置进行创建与使用AI基础库配置进行创建两种方式。\n' +
          '你可以使用基础配置进行创建，这将不会在创建前包含任何第三方依赖。' +
          '你也可以在创建时为函数分配一个AI基础库，这将为你的函数提前准备一定的第三方依赖。' +
          '当然，想要尝试更多基础库，可以随时进入函数的依赖管理界面修改基础库配置。',
      buildFunctionAILayer: '',
      publicLayerName: ''
    };
  },
  computed: {
    ...mapState('functions', ['serviceName', 'functionName'])
  },
  watch: {
    activeName: async function() {
      if (this.activeName === 'label2') {
        this.publicLayer = [];
        await getPublicLayerForLibrary().then((res) => {
          const data = [];
          let i;
          for (i = 0; i < res.Data.Names.length; i++) {
            data.push({ name: res.Data.Names[i], arn: res.Data.Arn[i], contains: res.Data.Contains[i] });
          }
          this.publicLayer = data;
        });
        const publicLayer = this.publicLayer.filter((x) => this.publicLayerName === x.name);
        this.buildFunctionAILayer = publicLayer[0].arn;
      }
    }
  },
  created() {
    this.$store.state.functions.usePublicLayers = '';
    this.$store.commit('functions/setTitle', '新建函数');
    if (this.type === 'updateFunction') {
      this.form.functionName = this.options.row.functionName;
      this.form.timeOut = this.options.row.timeOut;
      this.form.memorySize = this.options.row.memorySize;
    }
    getLayerDependencyForLibrary(this.serviceName, this.options.row.functionName).then((res) => {
      const publicLayerName = JSON.parse(res.BaseLayerJson);
      if (publicLayerName.length !== 0) {
        const name = publicLayerName[0].name;
        this.publicLayerName = name;
      }
    });
  },
  methods: {
    ...mapActions('functions', ['createAliFunction', 'updateAliFunction']),
    validateTimeout(rule, value, callback) {
      if (value < 5 || value > 86400) {
        callback(new Error('超时时间必须在5到86400之间！'));
      } else {
        callback();
      }
    },

    validateMemory(rule, value, callback) {
      // const vCPU = this.form.vCPU || 0.35; // 获取vCPU值，默认为0.35
      // const memoryGB = value / 1024; // 将内存大小转换为GB
      // const vCPURatio = vCPU / memoryGB; // 计算vCPU与内存大小的比例
      // if (value % 64 !== 0) {
      //   callback(new Error('内存大小必须是64的倍数！'));
      // } else if (vCPURatio < 0.25 || vCPURatio > 1) { // vCPU（核）大小与内存（GB）大小的比例必须设置在1:1到1:4之间
      //   const minMemory = Math.floor(Math.ceil(vCPU * 1024) / 64) * 64; // 根据vCPU计算最小内存，并向下取整到最接近的64的倍数
      //   const maxMemory = Math.floor(Math.floor(vCPU * 4096) / 64) * 64; // 根据vCPU计算最大内存，并向下取整到最接近的64的倍数
      //   callback(new Error(`vCPU（核）大小与内存（GB）大小的比例必须设置在1:1到1:4之间！在当前vCPU核数下${minMemory}MB到${maxMemory}MB`));
      // } else {
      //   callback();
      // }
      if (value < 128 || value > 3072) {
        callback(new Error('内存大小必须在128到3072之间！'));
      } else if (value % 64 !== 0) {
        callback(new Error('内存大小必须是64的倍数！'));
      } else {
        callback();
      }
    },
    getForm() {
      return this.form;
    },

    clickFunctions(type) {
      this.addParams = type;
    },
    createFun() {
      let usePublicLayers;
      if (this.activeName === 'label2') {
        usePublicLayers = this.buildFunctionAILayer;
      } else {
        usePublicLayers = '';
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          this.createAliFunction({
            library: {
              libraryName: this.serviceName
            },
            functions: this.form,
            usePublicLayers: usePublicLayers
          })
            .then((dat) => {
              this.$message.success('创建成功！');
            })
            .catch((err) => {
              console.log(err);
              this.$message.error('创建失败！');
            }).finally(() => {
              this.$router.push({
                name: 'MyLibrary'
              });
            });
        } else {
          this.$message.error('请正确填写表单！');
        }
      });
    },
    setFunctionLayer(arn, isSetPublicLayer) {
      if (isSetPublicLayer) {
        this.buildFunctionAILayer = arn;
      } else {
        this.buildFunctionAILayer = '';
      }
    },
    updateFun() {
      let usePublicLayers;
      if (this.activeName === 'label2') {
        usePublicLayers = this.buildFunctionAILayer;
      } else {
        usePublicLayers = '';
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          this.updateAliFunction({
            functionOption: {
              timeOut: this.form.timeOut,
              memorySize: this.form.memorySize
            },
            usePublicLayers: usePublicLayers,
            useFilePathJson: false
            // TODO 加入层的信息即可
          })
            .then(() => {
              this.$message.success('修改成功！');
            }).catch((err) => {
              console.log(err);
              this.$message.error('修改失败！');
            }).finally(() => {
              this.$router.push({
                name: 'MyLibrary'
              });
            });
        } else {
          this.$message.error('请正确填写表单！');
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.table-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%; /* 确保父元素具有高度 */
}

.el-table__body-wrapper {
  max-height: 100%;
  overflow: auto;
}

.mb-30 {
  margin-bottom: 30px;
}

label {
  width: 100px;
  line-height: 40px;
  text-align: left;
}

.input-style {
  width: 600px;
}
.display-window{
    word-break: normal;
    margin-right: 10px;
    margin-bottom: 10px;
    margin-left: 10px;
    font-weight: bolder;
    background:rgb(238, 238, 238);
}

.list-style {
  margin-bottom: 10px;

  .input-small-style {
    width: 150px;
  }

  i {
    line-height: 40px;
  }
}
</style>
